﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using TuDarmstadt.Informatik.TK.TnT.Captinect.Serializer;

namespace Player
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Stream stream;
        private WriteableBitmap colorBitmap;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void StartPlaying_Click(object sender, RoutedEventArgs e)
        {
            StartPlaying.IsEnabled = false;
            StopPlaying.IsEnabled = true;
            colorBitmap = new WriteableBitmap(640, 480, 96.0, 96.0, PixelFormats.Bgr32, null);
            Image.Source = colorBitmap;
            stream = File.Open("test.txt", FileMode.Open);

            BackgroundWorker worker = new BackgroundWorker();
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PlayImageCompleted);
            worker.RunWorkerAsync();
        }

        void PlayImageCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            if (stream.Position == stream.Length)
            {
                stream.Close();
                StartPlaying.IsEnabled = true;
                StopPlaying.IsEnabled = false;
            }
            else
            {
                SerializableColorImageFrame serializable = (SerializableColorImageFrame)formatter.Deserialize(stream);
                if (colorBitmap == null)
                {
                    colorBitmap = new WriteableBitmap(serializable.Width, serializable.Height, 96.0, 96.0, PixelFormats.Bgr32, null);
                }

                int pixelWidth = colorBitmap.PixelWidth;
                int pixelHeight = colorBitmap.PixelHeight;
                colorBitmap.WritePixels(
                    new Int32Rect(0, 0, pixelWidth, pixelHeight),
                    serializable.ColorPixels,
                    colorBitmap.PixelWidth * sizeof(int),
                    0);

                BackgroundWorker worker = new BackgroundWorker();
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PlayImageCompleted);
                worker.RunWorkerAsync();
            }
        }
    }
}
